package 并发.多线程;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * 信号量
 * @author 翟晓龙
 * @date 2022/4/22
 */
public class SemaphoreTest {

    public static void main(String[] args) {

        semaphoreCase(5);
    }

    /**
     * 路口一次最多n辆车通过
     */
    public static void semaphoreCase(int n){
        int count = 20;
        Semaphore semaphore = new Semaphore(n);
        CountDownLatch countDownLatch = new CountDownLatch(count);
        List<Integer> list = new ArrayList<>();

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        System.out.println("开始：");
        for (int i =0;i<count;i++){
            int finalI = i;
            executorService.submit(()->{
                System.out.println("车辆：" + finalI + "，等待通过路口。。。");
                try {
                    semaphore.acquire();
                    list.add(finalI);
                    System.out.println("🚗车辆：" + finalI + "，通过路口🚗");
                    Thread.sleep(20);
                    semaphore.release();
                } catch (InterruptedException e) {
                    System.out.println("车辆：" + finalI +"，通过失败！");
                    e.printStackTrace();
                }
            });
        }
        System.out.println("通过顺序：" + Arrays.toString(list.toArray()));
    }
}
